package com.ssyt.yt1.day29.backup;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 备份数据库
 * 
 * @author hf
 *
 */
public class BackUpDatabase {

	/** 拷贝到目标文件夹路径 */
	private String dest;

	private File logFile;
	/** 用于得到更新日志文件序号 */
	private int count = 0;

	/**
	 * 构造方法</pre>
	 * 
	 * @param dest
	 *            （必须）拷贝到目标文件夹路径
	 */
	public BackUpDatabase(String dest) {
		this.dest = dest;
		logFile = new File(dest + "/test.log");
	}

	/**
	 * 用于检测传入的文件夹是否存在，不存在就创建
	 * 
	 * @throws IOException
	 */
	private void createFile1() throws IOException {
		File file = new File(dest);
		if (!file.exists()) {
			file.mkdir();
		}
	}

	/**
	 * 根据输入输入的格式返回一个时间的字符串
	 * 
	 * @param style
	 * @return String
	 */
	private String getDatetime(String style) {
		Date date = new Date();
		String nowDate = new SimpleDateFormat(style).format(date);
		return nowDate;
	}

	/**
	 * 备份*.sql文件
	 * 
	 * @throws IOException
	 */
	private void backupToSQL() throws IOException {
		Runtime runtime = Runtime.getRuntime();
		String command = "mysqldump -uroot -p123456 test -r " + dest + "/test"
				+ getDatetime("yyyyMMddHHmmss") + ".sql";
		runtime.exec(command);
	}

	/**
	 * 初始化count
	 * 
	 * @param str
	 */
	private void setCount(String str) {
		int beginIndex = str.indexOf("号：") + 2;
		int endIndex = str.indexOf("，备份人");
		String getNum = str.substring(beginIndex, endIndex);
		count = Integer.parseInt(getNum);
	}

	/**
	 * <pre>
	 * 检测并创建日志文件，如果日志文件存
	 * 在，则获取序号并初始化count
	 * </pre>
	 * 
	 * @throws IOException
	 */
	private void setLogFile() throws IOException {
		if (!logFile.exists()) {
			logFile.createNewFile();
		} else {
			Scanner scan = new Scanner(logFile);
			String str = null;
			while (scan.hasNext()) {
				str = scan.nextLine();
			}
			setCount(str);
			if (scan != null) {
				scan.close();
			}
		}
	}

	/**
	 * 备份日志文件
	 * 
	 * @throws FileNotFoundException
	 */
	private void backupToLog() throws FileNotFoundException {
		OutputStream outputStream = null;
		outputStream = new FileOutputStream(logFile, true);
		String str = "序号：" + (++count) + "，备份人：hf001，备份时间："
				+ getDatetime("yyyy-MM-dd HH-mm-ss") + "，备份原因：xxx\r\n";
		byte[] bytes = str.getBytes();
		try {
			outputStream.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 对外提供的数据库备份方法
	 * 
	 * @throws IOException
	 */
	public void backup() throws IOException {
		createFile1();
		setLogFile();
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					backupToSQL();
					backupToLog();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}, 0, 3000);
	}
}
